How to call one constructor from another?
How to call one constructor from another?
I completed my post-graduation in 2013 in the engineering field. Engineering is the application of science and math to solve problems. Engineers figure out how things work and find practical uses for scientific discoveries. Scientists and inventors often get the credit for innovations that advance the human condition, but it is engineers who are instrumental in making those innovations available to the world. I love pet animals such as dogs, cats, etc.
Aryan Kumar
19-Aug-2023In Java, you can call one constructor from another using the
this()keyword. Thethis()keyword refers to the current object.To call one constructor from another, you need to use the
this()keyword followed by the name of the constructor you want to call. The constructor you want to call must be defined in the same class as the constructor that is calling it.Here is an example of how to call one constructor from another in Java:
Java
In this example, the
Person()constructor is the default constructor. ThePerson(String name)constructor takes a name parameter. The first line of thePerson(String name)constructor calls thePerson()constructor first. This is done to ensure that the fields of thePersonclass are initialized before the name property is set.Here is another example:
Java
In this example, the
Person(String name, int age)constructor calls thePerson(String name)constructor first. This is done to ensure that the name property is initialized before the age property is set.